package com.wholesale;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.wholesale.beans.BoughtGoods;
import com.wholesale.beans.GoodsInOrder;
import com.wholesale.beans.Order;
import com.wholesale.beans.PaymentMethod;
import com.wholesale.beans.ShippingMethod;
import com.wholesale.beans.UploadOrderResponse;
import com.wholesale.beans.UserAddress;
import com.wholesale.datas.DbHelperAdapter;
import com.wholesale.datas.ShopCar;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;
import com.wholesale.utils.Maths;

public class CheckOutLayout extends LinearLayout implements OnClickListener {
	private ViewFlipper viewFlipper;
	private Context context;
	private View baseView;
	private Button leftButton;
	private Button rightButton;
	private TextView headView;
	private RelativeLayout loadingLayout;

	private LinearLayout addressLayout;
	private RelativeLayout shipLayout;
	private RelativeLayout payLayout;
	private RelativeLayout giftLayout;
	private RelativeLayout balanceLayout;
	private RelativeLayout postscriptLayout;
	private TextView areaView;
	private TextView fullNameView;
	private TextView addressView;
	private TextView postalcodeView;
	private TextView phoneView;

	private TextView shippingMethodName;
	private TextView paymentMethodName;

	private UserAddress currentUserAddress;
	private int addressIndex = -1;
	private ShippingMethod currentShippingMethod;
	private int shippingIndex = -1;
	private PaymentMethod currentPaymentMethod;
	private int paymentIndex = -1;
	private double balance;
	private double goodsAmount = 0.00;
	private int goodsNumber = 0;
	ArrayList<ShopCar> shopCarList;
	ArrayList<BoughtGoods> boughtGoodsList;
	Order order = new Order();

	// davelin add
	private boolean isSubmitting = false;

	// 构造函数
	public CheckOutLayout(Context context, final ViewFlipper viewFlipper,
			ArrayList<ShopCar> shopCarList) {
		super(context);
		this.viewFlipper = viewFlipper;
		this.context = context;
		this.shopCarList = shopCarList;
		boughtGoodsList = new ArrayList<BoughtGoods>();
		ArrayList<GoodsInOrder> goodsInOrderList = new ArrayList<GoodsInOrder>();
		for (ShopCar shopCar : shopCarList) {
			goodsNumber = goodsNumber + shopCar.getCartInfo().getGoodsNumber();
			goodsAmount = Maths.add(goodsAmount, Maths.mul(shopCar
					.getCartInfo().getGoodsPrice(), shopCar.getCartInfo()
					.getGoodsNumber()));
			BoughtGoods boughtGoods = new BoughtGoods();
			boughtGoods.setGoodsId(shopCar.getGoodsId());
			boughtGoods.setGoodsNumber(shopCar.getCartInfo().getGoodsNumber());
			boughtGoodsList.add(boughtGoods);
			GoodsInOrder goodsInOrder = new GoodsInOrder();
			goodsInOrder.setGoodsId(shopCar.getGoodsId());
			goodsInOrder.setGoodsSn(shopCar.getCartInfo().getGoodsSn());
			goodsInOrder.setGoodsName(shopCar.getCartInfo().getGoodsName());
			goodsInOrder.setGoodsNumber(shopCar.getCartInfo().getGoodsNumber());
			goodsInOrder.setGoodsPrice(shopCar.getCartInfo().getGoodsPrice());
			goodsInOrder.setGoodsAttr(shopCar.getCartInfo().getGoodsAttr());
			goodsInOrderList.add(goodsInOrder);
		}
		order.setGoodsList(goodsInOrderList);

		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.orderdetail, this);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("Cart");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setText("Confirm");
		rightButton.setOnClickListener(this);
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("");
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);

		((TextView) baseView.findViewById(R.id.phone_lable))
				.setText("Phone&Mobile:");
		addressLayout = (LinearLayout) findViewById(R.id.addressLayout);
		addressLayout.setOnClickListener(this);
		shipLayout = (RelativeLayout) findViewById(R.id.shipMethodLayout);
		shipLayout.setOnClickListener(this);
		payLayout = (RelativeLayout) findViewById(R.id.payMethodLayout);
		payLayout.setOnClickListener(this);
		giftLayout = (RelativeLayout) findViewById(R.id.useGiftLayout);
		giftLayout.setOnClickListener(this);
		balanceLayout = (RelativeLayout) findViewById(R.id.useBalanceLayout);
		balanceLayout.setOnClickListener(this);
		postscriptLayout = (RelativeLayout) findViewById(R.id.orderPostLayout);
		postscriptLayout.setOnClickListener(this);

		areaView = (TextView) baseView.findViewById(R.id.area_text);
		fullNameView = (TextView) baseView.findViewById(R.id.fullname_text);
		addressView = (TextView) baseView.findViewById(R.id.address_text);
		postalcodeView = (TextView) baseView.findViewById(R.id.postalcode_text);
		phoneView = (TextView) baseView.findViewById(R.id.phone_text);
		shippingMethodName = (TextView) baseView
				.findViewById(R.id.shipMethod_text);
		paymentMethodName = (TextView) baseView
				.findViewById(R.id.payMethod_text);

		CurrentUserAddressAsync currentUserAddressAsync = new CurrentUserAddressAsync(
				context);
		currentUserAddressAsync.execute((Void) null);
	}

	public void setPaymentMethod(int selectIndex, PaymentMethod paymentMethod) {
		this.paymentIndex = selectIndex;
		this.currentPaymentMethod = paymentMethod;
		paymentMethodName.setText(currentPaymentMethod.getPayName());
		if (currentPaymentMethod.getPayName().equalsIgnoreCase(
				"Paypal (Credit Card / Debit Card)")) {
			String payName = "Paypal" + "\n" + "(Credit Card / Debit Card)";
			paymentMethodName.setText(payName);
		}

		if (currentPaymentMethod.getPayName().equalsIgnoreCase("Use balances")) {
			double total = Maths
					.add(goodsAmount, Constants
							.getTwoDecimalFloor(currentShippingMethod
									.getShippingFee()));
			this.balance = total;
			setUseBalance(total);
		} else {
			((TextView) baseView.findViewById(R.id.useBalance_text))
					.setText("");
		}
	}

	public void setShippingMethod(int selectIndex, ShippingMethod shippingMethod) {
		this.shippingIndex = selectIndex;
		this.currentShippingMethod = shippingMethod;
		shippingMethodName.setText(currentShippingMethod.getShippingName());
		// 如果是余额付款，重新计算总价
		if (currentPaymentMethod != null
				&& currentPaymentMethod.getPayName().equalsIgnoreCase(
						"Use balances")) {
			double orderAmount = Maths
					.add(goodsAmount, Constants
							.getTwoDecimalFloor(currentShippingMethod
									.getShippingFee()));
			setUseBalance(orderAmount);
		}

	}

	public void setUseBalance(double balance) {
		balance = Constants.getTwoDecimal(balance);
		this.balance = balance;
		((TextView) baseView.findViewById(R.id.useBalance_text)).setText(""
				+ balance);
	}

	public void setUserAddress(int selectIndex, UserAddress userAddress) {
		if (userAddress != null && addressIndex != selectIndex) {
			this.addressIndex = selectIndex;
			this.currentUserAddress = userAddress;
			String areaString = currentUserAddress.getCountryName();
			if (currentUserAddress.getProvinceName() != null) {
				areaString = areaString + ","
						+ currentUserAddress.getProvinceName();
			}
			if (currentUserAddress.getCityName() != null) {
				areaString = areaString + ","
						+ currentUserAddress.getCityName();
			}
			areaView.setText(areaString);
			fullNameView.setText(currentUserAddress.getConsignee());
			addressView.setText(currentUserAddress.getAddress());
			postalcodeView.setText(currentUserAddress.getZipcode());
			phoneView.setText(currentUserAddress.getMobile());

			currentShippingMethod = null;
			shippingIndex = -1;
			shippingMethodName.setText("");

			// 清空余额付款
			((TextView) baseView.findViewById(R.id.useBalance_text))
					.setText("");
			balance = 0;

			// 清空付款方式
			currentPaymentMethod = null;
			paymentIndex = -1;
			paymentMethodName.setText("");
		}
	}

	class CurrentUserAddressAsync extends AsyncTask<Void, Integer, UserAddress> {
		ProgressDialog pdialog;

		public CurrentUserAddressAsync(Context context) {
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected UserAddress doInBackground(Void... params) {
			return WebServiceClient.getCurrentUserAddress(
					Constants.loginResponse.getUserId(),
					Constants.loginResponse.getUserToken());
		}

		@Override
		protected void onPostExecute(UserAddress result) {
			// pdialog.dismiss();
			setUserAddress(-1, result);
			loadingLayout.setVisibility(View.GONE);
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	class ConfirmOrderAsync extends
			AsyncTask<Order, Integer, UploadOrderResponse> {
		ProgressDialog pdialog;

		public ConfirmOrderAsync(Context context) {
		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected UploadOrderResponse doInBackground(Order... params) {
			String orderSn = WebServiceClient.getNewOrderSn();
			Order order = params[0];
			order.setOrderSn(orderSn);
			UploadOrderResponse result = WebServiceClient.uploadOrder(order, 0,
					Constants.loginResponse.getUserToken());
			if (result.getReturnCode() == 0) {
				DbHelperAdapter dbHelperAdapter = new DbHelperAdapter(context);
				dbHelperAdapter.open();
				dbHelperAdapter.deleteAll();
				dbHelperAdapter.close();
				Intent myIntent = new Intent();// 创建Intent对象
				myIntent.setAction("com.wholesale.utils.UpdateUIService");
				myIntent.putExtra("from", "com.wholesale.CheckOutLayout");
				myIntent.putExtra("cmd", Constants.CMD_UPDATECAR_SERVICE);
				((Activity) getContext()).sendBroadcast(myIntent);
			}
			return result;
		}

		@Override
		protected void onPostExecute(UploadOrderResponse result) {
			loadingLayout.setVisibility(View.GONE);
			isSubmitting = false;
			if (result.getReturnCode() == 0) {
				dialog("Information", "success");

			} else {

				if (result.getReturnCode() == 4) {
					// 方式1，更新商品价格，立即提交上传
					// boolean modified = false;
					// for (CorrectGoodsPrice corrPrice : result
					// .getCorrectGoodsPriceLst()) {
					// for (GoodsInOrder g : order.getGoodsList()) {
					// if (corrPrice.getGoodsId() == g.getGoodsId()) {
					// modified = true;
					// g.setGoodsPrice(corrPrice.getPrice());
					// }
					// }
					// }
					// if (modified) {
					// CurrentUserAddressAsync currentUserAddressAsync = new
					// CurrentUserAddressAsync(
					// context);
					// currentUserAddressAsync.execute((Void) null);
					// }

					// 方式2，退回前一个view，更新购物车
					dialog("Waring", "goods price was updated. back to cart.");
					viewFlipper.showPrevious();
					View currView = viewFlipper.getCurrentView();
					if (currView instanceof Cart1Layout) {
						Cart1Layout cart1Layout = (Cart1Layout) currView;
						cart1Layout
								.updateList(result.getCorrectGoodsPriceLst());
					}
					viewFlipper.removeView(CheckOutLayout.this);

				} else {
					dialog("Error", result.getReason());
				}
			}
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

	public void dialog(String title, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("Confirm",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if (message != null && message.indexOf("success") != -1) {
							viewFlipper.showPrevious();
							viewFlipper.removeView(CheckOutLayout.this);

							// 如果是paypal支付方式
							if (order.getPayStatus() == 0
									&& order.getPayName()
											.equalsIgnoreCase(
													"Paypal (Credit Card / Debit Card)")) {
								PaypalLayout paypal = new PaypalLayout(context,
										viewFlipper, order);
								viewFlipper.addView(paypal);
								viewFlipper.showNext();
							}
						}
					}
				});
		builder.create().show();
	}

	@Override
	public synchronized void onClick(View v) {
		if (!isSubmitting) {
			switch (v.getId()) {
			case R.id.leftBtn:
				viewFlipper.showPrevious();
				viewFlipper.removeView(this);
				break;
			case R.id.rightBtn:
				if (currentPaymentMethod != null && currentUserAddress != null
						&& currentShippingMethod != null) {
					order.setUserId(Constants.loginResponse.getUserId());
					order.setOrderStatus(0);
					order.setPayStatus(0);
					order.setConsignee(currentUserAddress.getConsignee());
					order.setCountry(currentUserAddress.getCountry());
					order.setProvince(currentUserAddress.getProvince());
					order.setCity(currentUserAddress.getCity());
					order.setDistrict(currentUserAddress.getDistrict());
					order.setAddress(currentUserAddress.getAddress());
					order.setZipCode(currentUserAddress.getZipcode());
					order.setTel(currentUserAddress.getTel());
					order.setMobile(currentUserAddress.getMobile());
					order.setPostscript("");
					order.setShippingId(currentShippingMethod.getShippingId());
					order.setShippingName(currentShippingMethod
							.getShippingName());
					order.setPayId(currentPaymentMethod.getPayId());
					order.setPayName(currentPaymentMethod.getPayName());
					order.setGoodsAmount(goodsAmount);
					order.setShippingFee(Constants
							.getTwoDecimalFloor(currentShippingMethod
									.getShippingFee()));
					order.setInsureFee(0.00);
					order.setPayFee(currentPaymentMethod.getPayFee());
					// double orderAmount = goodsAmount
					// + Constants
					// .getTwoDecimalFloor(currentShippingMethod
					// .getShippingFee());
					double orderAmount = Maths.add(goodsAmount, Constants
							.getTwoDecimalFloor(currentShippingMethod
									.getShippingFee()));
					order.setOrderAmount(orderAmount);
					order.setGoodsNumber(goodsNumber);
					order.setMoneyPaid(0);
					if (currentPaymentMethod.getPayName().equalsIgnoreCase(
							"Use balances")) {
						// 检查余额是否足够
						if (orderAmount > OrderPaymentMethodLayout.userBalance) {
							dialog("Information",
									"Sorry, your balance is not enough to pay this order");
							isSubmitting = false;
							return;
						} else {
							order.setSurplus(balance);
							order.setPayStatus(2);
						}
					} else if (balance > 0) {
						if (balance < orderAmount) {
							order.setSurplus(balance);
							order.setPayStatus(0);
						} else if (balance == orderAmount) {
							dialog("Information",
									"Sorry, please choose the Use balances payment method");
							isSubmitting = false;
							return;
						} else {
							dialog("Information",
									"Sorry, balance is bigger than order amount");
							isSubmitting = false;
							return;
						}
					}

					ConfirmOrderAsync confirmOrderAsync = new ConfirmOrderAsync(
							context);
					confirmOrderAsync.execute(order);
					isSubmitting = true;
				} else {
					dialog("Information", "Please fill all infomation");
				}
				break;
			case R.id.addressLayout:
				MyAddressLayout myAddressLayout = new MyAddressLayout(context,
						viewFlipper, MyAddressLayout.CHECKOUT, addressIndex,
						currentUserAddress);
				viewFlipper.addView(myAddressLayout);
				viewFlipper.showNext();
				break;
			case R.id.shipMethodLayout:
				if (currentUserAddress != null
						&& currentUserAddress.getAddressId() != 0) {
					OrderShippingMethodLayout orderShippingMethodLayout = new OrderShippingMethodLayout(
							context, viewFlipper, currentShippingMethod,
							currentUserAddress.getAddressId(), shippingIndex,
							boughtGoodsList);
					viewFlipper.addView(orderShippingMethodLayout);
					viewFlipper.showNext();
				}

				break;
			case R.id.payMethodLayout:
				if (currentShippingMethod != null) {
					double total = Maths.add(goodsAmount, Constants
							.getTwoDecimalFloor(currentShippingMethod
									.getShippingFee()));
					OrderPaymentMethodLayout orderPaymentMethodLayout = new OrderPaymentMethodLayout(
							context, viewFlipper, total, paymentIndex,
							currentPaymentMethod);
					viewFlipper.addView(orderPaymentMethodLayout);
					viewFlipper.showNext();
				}
				break;
			case R.id.useBalanceLayout:
				if (currentPaymentMethod != null
						&& currentShippingMethod != null
						&& !currentPaymentMethod.getPayName().equalsIgnoreCase(
								"Use balances")) {
					double total = Maths.add(goodsAmount, Constants
							.getTwoDecimalFloor(currentShippingMethod
									.getShippingFee()));
					OrderUseBalanceLayout orderUseBalanceLayout = new OrderUseBalanceLayout(
							context, viewFlipper, total, balance);
					viewFlipper.addView(orderUseBalanceLayout);
					viewFlipper.showNext();
				} else {
					dialog("Information", "Please choose payment method");
				}
				break;
			default:
				break;
			}
		}
	}
}
